<?php 
 
class Chat extends CI_Controller {

	//Global variable  
    public $outputData;		//Holds the output data for each view
	public $loggedInUser;
	//public $username = $this->session->userdata('username');
	
	
	function __construct()
	{
		parent::__construct();
		
		if (!isset($_SESSION['chatHistory'])) {
	$_SESSION['chatHistory'] = array();	
}

	if (!isset($_SESSION['openChatBoxes'])) {
		$_SESSION['openChatBoxes'] = array();	
	}
	$this->load->model('chat_model');
	$this->load->model('common_model');
	$_SESSION['username'] = $this->session->userdata('user_id');
	}
	
	
	public function index()
    {
		
		//Get all users
		//$this->outputData['listOfUsers']= $this->users_model->getUsers();
		
		//echo '<pre>';
		//$userdata  = $this->session->all_userdata();
		
		//$this->outputData['session_dataa'] = $userdata;
		//	print_r($_SESSION);			
		//echo 'sadasd';	
		// $this->load->view('chat/userList',$this->outputData);
    }
	
function chatHeartbeat() {	
	$queries = $this->chat_model->chatHeartbeat();	
	$items = '';
	$chatBoxes = array();

	foreach($queries as $chat) {

		if (!isset($_SESSION['openChatBoxes'][$chat['from']]) && isset($_SESSION['chatHistory'][$chat['from']])) {
			$items = $_SESSION['chatHistory'][$chat['from']];
		}

		$chat['message'] = $this->sanitize($chat['message']);
		$from = $chat['from'];
		$ucname = $this->common_model->get_username_id($from);
		$items .= <<<EOD
					   {
			"s": "0",
			"f": "{$from}",
			"m": "{$chat['message']}",
			"u": "{$ucname}",
	   },
EOD;

	if (!isset($_SESSION['chatHistory'][$chat['from']])) {
		$_SESSION['chatHistory'][$chat['from']] = '';
		
	}

	$_SESSION['chatHistory'][$chat['from']] .= <<<EOD
						   {
			"s": "0",
			"f": "{$chat['from']}",
			"m": "{$chat['message']}",
			"u": "{$chat['username']}",
	   },
EOD;
		
		unset($_SESSION['tsChatBoxes'][$chat['from']]);
		$_SESSION['openChatBoxes'][$chat['from']] = $chat['sent'];
	}

	if (!empty($_SESSION['openChatBoxes'])) {
	foreach ($_SESSION['openChatBoxes'] as $chatbox => $time) {
		if (!isset($_SESSION['tsChatBoxes'][$chatbox])) {
			$now = time()-strtotime($time);
			$time = date('g:iA M dS', strtotime($time));

			$message = "Sent at $time";
			if ($now > 180) {
				$items .= <<<EOD
{
"s": "2",
"f": "$chatbox",
"m": "{$message}"
},
EOD;

	if (!isset($_SESSION['chatHistory'][$chatbox])) {
		$_SESSION['chatHistory'][$chatbox] = '';
	}

	$_SESSION['chatHistory'][$chatbox] .= <<<EOD
		{
"s": "2",
"f": "$chatbox",
"m": "{$message}"
},
EOD;
			$_SESSION['tsChatBoxes'][$chatbox] = 1;
		}
		}
	}
}

	$this->chat_model->update_chatHeartbeat();

	if ($items != '') {
		$items = substr($items, 0, -1);
	}
header('Content-type: application/json');
?>
{
		"items": [
			<?php echo $items;?>
        ]
}

<?php
			exit(0);
}



function startChatSession() {	
	$items = '';	
	if (!empty($_SESSION['openChatBoxes'])) {
		foreach ($_SESSION['openChatBoxes'] as $chatbox => $void) {
			$items .= $this->chatBoxSession($chatbox);
		}
	}

	if ($items != '') {
		$items = substr($items, 0, -1);
	}

header('Content-type: application/json');
?>
{
		"username": "<?php echo $this->session->userdata('username');?>",
		"items": [ <?php echo $items;?>]
}
<?php
	exit(0);
}

function chatBoxSession($chatbox) {
	
	$items = '';
	
	if (isset($_SESSION['chatHistory'][$chatbox])) {
		$items = $_SESSION['chatHistory'][$chatbox];
	}

	return $items;
}

function closeChat() {

	unset($_SESSION['openChatBoxes'][$_POST['chatbox']]);	
	echo "1";
	exit(0);
}


function sanitize($text) {
	$text = htmlspecialchars($text, ENT_QUOTES);
	$text = str_replace("\n\r","\n",$text);
	$text = str_replace("\r\n","\n",$text);
	$text = str_replace("\n","<br>",$text);
	return $text;
}


/**
* @author: pratik
* chat model starts 
*/

function sendChat() {
	
	$from = $_SESSION['username'];
	$to = $_POST['to'];
	 $message = $_POST['message'];
 print_r($_SESSION);

	$_SESSION['openChatBoxes'][$_POST['to']] = date('Y-m-d H:i:s', time());
	
$messagesan = $this->sanitize($message);

	if (!isset($_SESSION['chatHistory'][$_POST['to']])) {
		$_SESSION['chatHistory'][$_POST['to']] = '';
	}

	$_SESSION['chatHistory'][$_POST['to']] .= <<<EOD
					   {
			"s": "1",
			"f": "{$to}",
			"m": "{$messagesan}"
			"u": "{$this->common_model->get_username_id($to)}",
	   },
EOD;
	unset($_SESSION['tsChatBoxes'][$_POST['to']]);
	
	$insert = array(
	'from' => mysql_real_escape_string($from),
	'to' => mysql_real_escape_string($to),
	'message' => mysql_real_escape_string($message),
	'sent' => date('Y-m-d H:i:s', time()),
	);
	$this->chat_model->sendChat($insert);
	echo "1";
	//print_r($_SESSION);
	exit(0);
}


	public function get_chat_name($user_id){	
		echo $this->common_model->get_username_id($user_id);
	}

function setUserCookie($name='',$value ='',$expire = '',$domain='',$path = '/',$prefix ='')
	 {
	 		 $cookie = array(
                   'name'   =>$name,
                   'value'  => $value,
                   'expire' => $expire,
                   'domain' => $domain,
                   'path'   => $path,
                   'prefix' => $prefix,
               );
			   set_cookie($cookie); 
	 }//End of setUserCookie Function	
	 
	 function getUserCookie($name='')
	 {
		 $val=get_cookie($name,TRUE); 
		return $val;
	 }//End of getUserCookie Function	
	 
	 //End of getUserCookie Function	


}

